package run.jingjing.websocket.timer;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import lombok.extern.slf4j.Slf4j;
import run.jingjing.websocket.model.LWsTopic;
import run.jingjing.websocket.model.RunningTopic;
import java.util.concurrent.TimeUnit;

/**
 * @author: jingjing
 * @date: 2021/6/24
 * @description:
 */
@Slf4j
public class LocalCleanSessionTask implements TimerTask {

    private RunningTopic runningTopic;

    private HashedWheelTimer timer;

    private Integer intervalSecond = 5;

    public LocalCleanSessionTask(RunningTopic runningTopic, HashedWheelTimer timer, Integer intervalSecond) {
        this.runningTopic = runningTopic;
        this.timer = timer;
        this.intervalSecond = intervalSecond;
        if (runningTopic == null || timer == null) {
            log.error("constructor param of LocalOnlineCountTask is null");
            throw new RuntimeException();
        }
    }

    @Override
    public void run(Timeout timeout) {
        LWsTopic topic = runningTopic.getlWsTopic();
        topic.values().stream().filter(i -> !i.getSession().isOpen()).forEach(i -> topic.remove(i.getUserId()));
        Timeout newTimeout = timer.newTimeout(this, intervalSecond, TimeUnit.SECONDS);
        runningTopic.removeTimeout(timeout);
        runningTopic.addTimeouts(newTimeout);
    }

}
